<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>床位管理系统</title>
    <!-- 添加Bootstrap和Font Awesome -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        body {
            font-family: 'Microsoft YaHei', sans-serif;
            background-color: rgb(255, 255, 255);
            margin: 0;
        }
        .container {
            max-width: 1200px;
            margin: 0 auto;
            background-color: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        .search-bar {
            display: flex;
            margin-bottom: 20px;
            align-items: center;
        }
        .search-input {
            flex: 1;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 4px;
            margin-right: 10px;
        }

        .btn {
            width: 200px;
            padding: 10px 15px;
            margin-right: 6px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-weight: bold;
        }
        .btn-query {
            background-color: #1890ff;
            color: white;
        }
        .btn-select {
            background-color: #52c41a;
            color: white;
        }
        .btn-add {
            background-color: #faad14;
            color: white;
            z-index: 99999;
        }
        .btn-delete {
            background-color: #ff4d4f;
            color: white;
        }
        .beds-container {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
            gap: 20px;
        }
        .bed-card {
            border: 1px solid #e8e8e8;
            border-radius: 6px;
            padding: 15px;
            position: relative;
        }
        .bed-status {
            position: absolute;
            top: 15px;
            right: 15px;
            width: 20px;
            height: 20px;
            border-radius: 50%;
        }
        .status-occupied {
            background-color: #1890ff;
        }
        .status-empty {
            background-color: #52c41a;
        }
        .status-cleaning {
            background-color: #faad14;
        }
        .status-repairing {
            background-color: #ff4d4f;
        }
        .bed-info {
            margin-bottom: 10px;
        }
        .bed-title {
            font-weight: bold;
            margin-bottom: 5px;
        }
        .bed-actions {
            display: flex;
            justify-content: flex-end;
            margin-top: 10px;
        }
        .action-btn {
            padding: 5px 10px;
            margin-left: 10px;
            border: 1px solid #d9d9d9;
            border-radius: 4px;
            cursor: pointer;
        }
        .action-edit {
            color: #1890ff;
            border-color: #1890ff;
        }
        .action-delete {
            color: #ff4d4f;
            border-color: #ff4d4f;
        }
        .status-legend {
            display: flex;
            justify-content: flex-end;
            margin-bottom: 15px;
        }
        .legend-item {
            display: flex;
            align-items: center;
            margin-left: 15px;
        }
        .legend-color {
            width: 15px;
            height: 15px;
            border-radius: 50%;
            margin-right: 5px;
        }
        .form-control, .form-select {
            border-radius: 6px;
            padding: 10px 40px;
        }
    </style>

</head>
<body>

<div class="container">

       <div class="search-bar">
           <div class="mb-3">
            <select class="form-select" id="building" required>
                <option value="">请选择楼栋</option>
                <option value="1栋">1栋</option>
                <option value="2栋">2栋</option>
                <option value="3栋">3栋</option>
                <option value="4栋">4栋</option>
                <option value="5栋">5栋</option>
                <option value="6栋">6栋</option>
                <option value="7栋">7栋</option>
                <option value="8栋">8栋</option>
                <option value="9栋">9栋</option>
                <option value="10栋">10栋</option>

            </select>
           </div>
           <div class="mb-3">
               <select class="form-select" id="floor" required>
                   <option value="">请选择楼</option>
                   <option value="1">1楼</option>
                   <option value="2">2楼</option>
                   <option value="3">3楼</option>
                   <option value="4">4楼</option>
                   <option value="5">5楼</option>
                   <option value="6">6楼</option>
                   <option value="7">7楼</option>
                   <option value="8">8楼</option>
                   <option value="9">9楼</option>
                   <option value="10">10楼</option>
               </select>
           </div>
           <div class="mb-3">
               <select class="form-select" id="room" required>
                   <option value="">请选择房</option>
                   <option value="101">101</option>
                   <option value="102">102</option>
                   <option value="103">103</option>
                   <option value="104">104</option>
                   <option value="105">105</option>
                   <option value="106">106</option>
                   <option value="107">107</option>
                   <option value="108">108</option>
                   <option value="109">109</option>
                   <option value="110">110</option>
               </select>
           </div>
           <input type="text" class="search-input" id="searchInput" placeholder="请输入床位编号">
           <button type="button" class="btn btn-query" id="searchBtn" style="background-color: #2d9249">查询</button>
           <c:if test="${user.role eq 'admin' || user.role eq 'dormitory'}">
           <button type="button" class="btn btn-add btnnn" id="btn-1" style="background-color: #0d6efd">新增</button>
           </c:if>
       </div>

       <div class="status-legend">
           <div class="legend-item">
               <div class="legend-color" style="background-color: #1890ff;"></div>
               <span>有人</span>
           </div>
           <div class="legend-item">
               <div class="legend-color" style="background-color: #52c41a;"></div>
               <span>无人</span>
           </div>
       </div>

      <div class="beds-container">
<%--           <div class="bed-card">--%>
<%--               <div class="bed-status status-empty"></div>--%>
<%--               <div class="bed-info">--%>
<%--                   <div class="bed-title">序号：${bed_number}床/${room_number}房/${floor}楼</div>--%>
<%--                   <div>持有人：${name}</div>--%>
<%--                   <div>手机号：${phone}</div>--%>
<%--                   <div>更新时间：${student_time}</div>--%>
<%--               </div>--%>
<%--               <div class="bed-actions">--%>
<%--                   <button class="action-btn action-edit">修改</button>--%>
<%--                   <button class="action-btn action-delete">删除</button>--%>
<%--               </div>--%>
<%--           </div>--%>
      </div>
</div>
<!-- 新增床位模态框 -->
<div class="modal fade" id="addBedModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header bg-primary text-white">
                <h5 class="modal-title">
                    <i class="fas fa-plus-circle me-2"></i>新增床位
                </h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <form id="addBedForm">
                    <div class="mb-3">
                        <label for="bedNumber" class="form-label">床位编号</label>
                        <input type="text" class="form-control" id="bedNumber" required>
                    </div>
                    <div class="mb-3">
                        <label for="roomNumber" class="form-label">房间号</label>
                        <input type="text" class="form-control" id="roomNumber" required>
                    </div>
                    <div class="mb-3">
                        <label for="floorNumber" class="form-label">楼层</label>
                        <input type="number" class="form-control" id="floorNumber" min="1" required>
                    </div>
                    <div class="mb-3">
                        <label for="bedStatus" class="form-label">床位状态</label>
                        <select class="form-select" id="bedStatus" required>
                            <option value="occupied">有人</option>
                            <option value="empty" selected>无人</option>
                        </select>
                    </div>
                    </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
                    <i class="fas fa-times me-1"></i>取消
                </button>
                <button type="button" class="btn btn-primary" id="confirmAddBed">
                    <i class="fas fa-check me-1"></i>确认添加
                </button>
            </div>
        </div>
    </div>
</div>
<style>
/* 添加到现有的style标签中 */
.modal-header.bg-primary {
    background-color: #1890ff !important;
}
.modal-content {
    border-radius: 10px;
    overflow: hidden;
    box-shadow: 0 5px 15px rgba(0,0,0,0.2);
}
.form-control, .form-select {
    border-radius: 6px;
    padding: 10px 49px;
    margin-top: 16px;
}
.form-label {
    font-weight: 500;
    margin-bottom: 8px;
}
/* 表单验证样式 */
.was-validated .form-control:invalid,
.was-validated .form-select:invalid {
    border-color: #dc3545;
}
.was-validated .form-control:valid,
.was-validated .form-select:valid {
    border-color: #28a745;
}
.invalid-feedback {
    display: none;
    width: 100%;
    margin-top: 0.25rem;
    font-size: 0.875em;
    color: #dc3545;
}
.was-validated .form-control:invalid ~ .invalid-feedback,
.was-validated .form-select:invalid ~ .invalid-feedback {
    display: block;
}
</style>

<script>
    document.addEventListener('DOMContentLoaded', function() {
        // 确保Bootstrap和jQuery已加载
        if (typeof bootstrap === 'undefined' || typeof $ === 'undefined') {
            console.error('Bootstrap或jQuery未正确加载');
            return;
        }

        // 初始化模态框
        const addBedModal = new bootstrap.Modal(document.getElementById('addBedModal'), {
            backdrop: 'static',
            keyboard: false
        });




    });



    // 确认添加按钮点击事件
    document.getElementById('confirmAddBed').addEventListener('click', function() {
        // 获取表单数据
        const bedData = {
            bedNumber: document.getElementById('bedNumber').value,
            roomNumber: document.getElementById('roomNumber').value,
            floorNumber: document.getElementById('floorNumber').value,
            status: document.getElementById('bedStatus').value
        };

        // 表单验证
        if (!bedData.bedNumber || !bedData.roomNumber || !bedData.floorNumber) {
            alert('请填写所有必填字段');
            return;
        }

        // 发送AJAX请求
        fetch(`<%=request.getContextPath()%>/managementController?op=xinzen`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: new URLSearchParams(bedData).toString()
        })
            .then(response => response.text())
            .then(data => {
                if(data === 'success') {
                    alert('新增床位成功');
                    addBedModal.hide();
                    // 刷新床位列表
                    document.getElementById('searchBtn').click();
                } else {
                    alert(data);
                }
            })
            .catch(error => {
                console.error('新增错误:', error);
                alert(error.message);
            });
    });


    // 新增按钮点击事件 btnnn
    document.getElementById('btn-1').addEventListener('click', function() {
        debugger
        const addBedModal3 = $('#addBedModal').modal({
            backdrop: false // 禁用遮罩层，允许点击页面其他部分
        });
        addBedModal3.modal('show')


    });
    // 修改查询按钮的fetch请求
    document.getElementById('searchBtn').addEventListener('click', function() {
        const building = document.getElementById('building').value.trim();
        const floor = document.getElementById('floor').value.trim();
        const room = document.getElementById('room').value.trim();
        const searchInput = document.getElementById('searchInput').value.trim();

        // 构建查询参数
        let params = new URLSearchParams();
        if(building) params.append('building_name', building);
        if(floor) params.append('floor', floor);
        if(room) params.append('room_number', room);
        if(searchInput) params.append('bed_number', searchInput);

        fetch('<%=request.getContextPath()%>/managementController?op=chaxu&' + params.toString(), {
            method: 'POST',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/x-www-form-urlencoded'
            }
        })
        .then(response => {
            console.log('响应状态:', response.status); // 调试输出
            if (!response.ok) {
                throw new Error('网络响应不正常');
            }
            return response.json();
        })
        .then(data => {
            console.log('返回数据:', data); // 调试输出
            const bedsContainer = document.querySelector('.beds-container');
            bedsContainer.innerHTML = '';
        
            if (data && data.length > 0) {
                data.forEach(bed => {
                    const bedCard = createBedCard(bed);
                    bedsContainer.appendChild(bedCard);
                });
            } else {
                bedsContainer.innerHTML = '<div class="text-center py-4">没有找到匹配的床位</div>';
            }
        })
        .catch(error => {
            console.error('查询错误:', error);
            alert('查询失败: ' + error.message);
        });
    });

    // 创建床位卡片函数
    function createBedCard(bed) {
        const card = document.createElement('div');
        card.className = 'bed-card';
        card.dataset.bedNumber = bed.bed_number;
        card.dataset.bed_id = bed.bed_id;
    
        // 根据床位是否有人设置颜色类和显示内容
        let statusClass;
        let phoneDisplay = '暂无';
        let timeDisplay = '未更新';
        
        if (bed.name && bed.name.trim() !== '') {
            statusClass = 'status-occupied'; // 蓝色 - 有人
            phoneDisplay = bed.phone || '暂无';
            timeDisplay = bed.student_time || '未更新';
        } else {
            statusClass = 'status-empty';    // 绿色 - 无人
            phoneDisplay = '暂无';  // 无人时清空手机号
            timeDisplay = '未更新';   // 无人时清空时间
        }
    
        card.innerHTML =
            '<div class="bed-status1 ' + bed.bed_id + '"></div>' +
            '<div class="bed-status ' + statusClass + '"></div>' +
            '<div class="bed-info">' +
            '<div class="bed-title">'+bed.building_name+'/' + bed.floor + '楼/' + bed.room_number + '房/' + bed.bed_number + '床</div>' +
            '<div>持有人：' + (bed.name || '暂无') + '</div>' +
            '<div>手机号：' + phoneDisplay + '</div>' +
            '<div>更新时间：' + timeDisplay + '</div>' +
            '</div>' +
            '<div class="bed-actions">' +
             '<c:if test="${user.role eq 'admin' || user.role eq 'dormitory'}">'+
            '<button class="action-btn action-delete" onclick="deleteBed(this)">删除</button>' +
            '</c:if>'+
            '</div>';
    
        return card;
    }
    function deleteBed(button) {
    if (!confirm('确定要删除这个床位吗？')) {
        return;
    }

    const card = button.closest('.bed-card');
    const bedId = card.dataset.bed_id;
    
    // 使用JavaScript原生的encodeURIComponent函数
        const encodedValue = bedId;

    fetch('<%=request.getContextPath()%>/managementController?op=shanchu&bed_id='+bedId, {
        method: 'POST',
        headers: {
            'Accept': 'application/json'
        }
    })
    .then(data => {
        if (data=="删除成功") {
            alert('删除成功');
            card.remove(); // 从DOM中移除该床位卡片
        } else {
            alert('删除失败: ' + (data.message || '未知错误'));
        }
    })
    .catch(error => {
        console.error('删除错误:', error);
        alert('删除失败: ' + error.message);
    });
}  // 这里添加了缺失的右花括号

</script>
</body>
</html>